<?php
class tencentCDN {
    public $options;
    private $host;
    private $apiurl;
    private $service;
    private $version;

    function __construct($bucket='') {
        $this->options = get_option('tencent_cdn');
		$this->options = unserialize($this->options);
        $this->host = 'cdn.tencentcloudapi.com';
        $this->apiurl = 'https://' . $this->host;
        $this->service = 'cdn';
        $this->version = '2018-06-06';
    }
    
    //Headers
    private function headers($headers, $method='POST') {
        switch($method) {
            case 'POST' :
                $content_type = 'application/json; charset=utf-8';
                break;
            case 'GET' :
                $content_type = 'application/x-www-form-urlencoded';
                break;
            case 'PUT' :
                $content_type = 'Content-Type: multipart/form-data';
                break;
            default :
        }
        $defaults = array(
            'Host' => $this->host,
            'Content-Type' => $content_type,
            'X-TC-Version' => $this->version,
            'X-TC-Timestamp' => time(),
        );
        return wp_parse_args($headers, $defaults);
    }

    //处理参数
    private function headers_list($headers) {
        $list = array();
        foreach($headers as $key=>$val) {
            $key = strtolower(trim($key));   
            $val = strtolower(trim($val));
            $list[$key] = $key . ':' . $val;
        }
        ksort($list);
        return $list;
    }

    //签名
    private function sign($headers, $urlparams='', $payload='', $method='POST') {
        $canonical_uri = '/';
        $algorithm = 'TC3-HMAC-SHA256';
        $request_timestamp = $headers['X-TC-Timestamp'];
        $date = date('Y-m-d', $request_timestamp);

        $headers = $this->headers_list($headers);
        $canonical_headers = join("\n", $headers) . "\n";
        $signed_headers = join(';', array_keys($headers));

        $payload = hash('SHA256', $payload);

        $canonical_request = $method . "\n"
            . $canonical_uri . "\n"
            . $urlparams . "\n"
            . $canonical_headers . "\n"
            . $signed_headers . "\n"
            . $payload;
            
        $hashed_canonical_request = hash('SHA256', $canonical_request);
        $credential_scope = $date . '/' . $this->service . '/tc3_request';
        $string_tosign = $algorithm . "\n"
            . $request_timestamp . "\n"
            . $credential_scope . "\n"
            . $hashed_canonical_request;

        $secret_date = hash_hmac('SHA256', $date, 'TC3' . $this->options['secret_key'], true);
        $secret_service = hash_hmac('SHA256', $this->service, $secret_date, true);
        $secret_signing = hash_hmac('SHA256', 'tc3_request', $secret_service, true);
        $signature = hash_hmac('SHA256', $string_tosign, $secret_signing);
        $authorization = $algorithm . ' '
            . 'Credential=' . $this->options['secret_id'] . '/' . $credential_scope . ', '
            . 'SignedHeaders=' . $signed_headers . ', '
            . 'Signature=' . $signature;

        return $authorization;
    }

    //查询刷新用量
    public function quota() {
        if(!$this->options) return;
        $headers = $this->headers([
            'X-TC-Action' => 'DescribePurgeQuota',
        ]);

        $sign = $this->sign($headers);
        $headers['Authorization'] = $sign;

        $response = wp_remote_post($this->apiurl, array(
            'headers' => $headers,
            'sslverify' => true,
        ));

        if(is_wp_error($response)) {
            return;
        }

        $data = json_decode($response['body'], true);
        if(isset($data['Response']['UrlPurge'])) {
            return [
                'UrlPurge' => $data['Response']['UrlPurge'],
                'PathPurge' => $data['Response']['PathPurge'],
            ];
        }

        return;
    }

    //查询域名详情
    public function domains_config($domain='') {
        if(!$this->options) return;

        $headers = $this->headers([
            'X-TC-Action' => 'DescribeDomainsConfig',
        ]);

        if(!$domain) {
            $home_url = home_url();
            $parse_url = parse_url($home_url);
            $domain = $parse_url['host'];
        }

        if($domain && !is_array($domain)) {
            $domain = [$domain];
        }

        $body = array(
            'Filters' => array([
                'Name' => 'domain',
                'Value' => $domain,
            ]),
        );
        $body = json_encode($body);

        $sign = $this->sign($headers, '',  $body);
        $headers['Authorization'] = $sign;

        $response = wp_remote_post($this->apiurl, array(
            'headers' => $headers,
            'sslverify' => true,
            'body' => $body,
        ));

        if(is_wp_error($response)) {
            return $response->get_error_message();
        }

        $response = json_decode($response['body'], true);
        if(isset($response['Response']['Error']['Message'])) {
            return $response['Response']['Error']['Message'];
        }

        return $response['Response']['Domains'][0];
    }

    //刷新缓存
    public function flush($urls, $type='UrlPurge') {
        if(!$this->options) return '请设置API信息';

        $urls_key = 'Urls';
        $body = [];

        $headers = $this->headers([
            'X-TC-Action' => 'PurgeUrlsCache',
        ]);

        if($type == 'PathPurge') {
            $body['FlushType'] = 'flush';
            $headers['X-TC-Action'] = 'PurgePathCache';
            $urls_key = 'Paths';
        }

        for($i=0; $i < count($urls); $i++) {
            $body[$urls_key][$i] = $urls[$i];
        }

        $body = json_encode($body);
        $sign = $this->sign($headers, '',  $body);
        $headers['Authorization'] = $sign;

        $response = wp_remote_post($this->apiurl, array(
            'headers' => $headers,
            'sslverify' => true,
            'body' => $body,
        ));

        if(is_wp_error($response)) {
            return $response->get_error_message();
        }

        $response = json_decode($response['body'], true);
        if(!isset($response['Response']['TaskId'])) {
            return $response['Response']['Error']['Message'];
        }

        return true;
    }

    //刷新URL缓存
    public function flush_urls($urls) {
        return $this->flush($urls, 'UrlPurge');
    }

    //刷新目录缓存
    public function flush_paths($urls) {
        return $this->flush($urls, 'PathPurge');
    }

}
?>